document.addEventListener('DOMContentLoaded', function () {
  const submitBtn = document.getElementById('submit-question-btn');
  const clearBtn = document.getElementById('clear-question-btn');
  const questionInput = document.getElementById('question-input');
  const categorySelect = document.getElementById('category-select');
  const answerBox = document.getElementById('qa-response');
  const answerText = document.getElementById('qa-answer');

  submitBtn.addEventListener('click', async function () {
    const questionText = questionInput.value.trim();
    const categoryName = categorySelect.value;
    const userID = localStorage.getItem('userid');

    if (!userID) {
      alert('请先登录后再提交问题');
      return;
    }

    if (!questionText) {
      alert('请输入问题内容');
      return;
    }

    // 构造数据 + 提交保存问题到后端
    const data = {
      userID: parseInt(userID),
      questionText,
      categoryName,
      createTime: new Date().toISOString()
    };

    try {
      const response = await axios.post('http://localhost:8080/api/questions/add', data);
      const res = response.data;
      if (res.code !== 200) {
        alert(res.message || '❌ 问题提交失败，请稍后再试');
        return;
      }

      // 显示回答区域
      answerBox.classList.remove('hidden');
      answerText.textContent = '🤖 AI 正在思考中，请稍候...';

      submitBtn.disabled = true;
      submitBtn.innerText = '提交中...';

      // 构造 AI 请求
      const fullPrompt = `分类: ${categoryName}\n问题: ${questionText}`;
      const aiRes = await fetch('https://api.siliconflow.cn/v1/chat/completions', {
        method: 'POST',
        headers: {
          'Authorization': 'Bearer sk-uqjxfxixtbawekrctxjrpzchyqwcbgbzinvzrmxxgzxnzivm',
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          model: "deepseek-ai/DeepSeek-R1",
          messages: [{ role: "user", content: fullPrompt }],
          stream: true, // ✅ 流式开启
          max_tokens: 2048,
          temperature: 0.7,
          top_p: 0.7,
          top_k: 50,
          frequency_penalty: 0.5
        })
      });

      if (!aiRes.ok) throw new Error('AI 请求失败');

      // 流式读取响应
      const reader = aiRes.body.getReader();
      const decoder = new TextDecoder('utf-8');
      let buffer = '';
      answerText.textContent = '';

      while (true) {
        const { value, done } = await reader.read();
        if (done) break;
        buffer += decoder.decode(value, { stream: true });

        // 处理 JSON 格式的 SSE 数据块
        const lines = buffer.split('\n');

        for (const line of lines) {
          if (line.startsWith('data: ')) {
            const jsonStr = line.replace('data: ', '').trim();
            if (jsonStr === '[DONE]') continue;
            try {
              const delta = JSON.parse(jsonStr);
              const token = delta?.choices?.[0]?.delta?.content;
              if (token) {
                answerText.textContent += token;
              }
            } catch (e) {
              console.warn('解析失败:', jsonStr);
            }
          }
        }

        // 清理 buffer
        buffer = lines[lines.length - 1]; // 保留最后一行未完整内容
      }

      questionInput.value = '';

    } catch (err) {
      console.error('请求错误:', err);
      alert('发生错误，请稍后再试');
    } finally {
      submitBtn.disabled = false;
      submitBtn.innerHTML = '<i class="fa fa-paper-plane mr-1"></i> 提交问题';
    }
  });

  clearBtn.addEventListener('click', () => {
    questionInput.value = '';
    answerText.textContent = '';
    answerBox.classList.add('hidden');
  });
});
